import { getWorkflowStore, WorkflowContext } from "@/context/WorkflowContext";
import { storeNodes2RuntimeNodes } from "@/function/utils";
import { Box, Drawer, DrawerContent, Textarea } from "@chakra-ui/react";
import collect from "collect.js";
import { useCallback, useContext, useEffect, useState } from "react";



export const useDebug = () => {
  const { onStartNodeDebug,setNodes,edges } = useContext(WorkflowContext);

  const [runtimeNodeId, setRuntimeNodeId] = useState<string>();
  const [runtimeNodes, setRuntimeNodes] = useState<[]>();
  const [runtimeEdges, setRuntimeEdges] = useState<[]>();

  const flowData2StoreDataAndCheck = useCallback(async () =>{
    const { nodes } = await getWorkflowStore();
    return JSON.stringify({nodes,edges})
  },[])


  const openDebugNode = useCallback(
      async ({entryNodeId}:any)=>{
        
        const {
          nodes,
          edges
        } = JSON.parse(await flowData2StoreDataAndCheck());
        console.log('openDebugNode:node1',nodes)
          setNodes((state:any) =>
              state.map((node:any) => ({
                ...node,
                data: {
                  ...node.data,
                  debugResult: undefined
                }
              }))
          );
          console.log('openDebugNode:node2',nodes)
          
          const runtimeNodes = storeNodes2RuntimeNodes(nodes, [entryNodeId]);
          const runtimeEdges = edges.map((edge:any) =>
            edge.target === entryNodeId
              ? {
                  ...edge,
                  status: 'active'
                }
              : {
                  ...edge,
                  status: 'waiting'
                }
          );
          console.log('openDebugNode',runtimeNodes,runtimeEdges,entryNodeId)
          setRuntimeNodeId(entryNodeId);
          setRuntimeNodes(runtimeNodes);
          setRuntimeEdges(runtimeEdges);
      },
      [flowData2StoreDataAndCheck,setNodes]  
  )

    useEffect(() => {
      console.log('openDebugNode:runtimeNodes updated:', runtimeNodes);
    }, [runtimeNodes]);
    

  const onClose = () => {
    setRuntimeNodeId(undefined);
    setRuntimeNodes(undefined);
    setRuntimeEdges(undefined);
  };

  const DebugInputModal = useCallback(() => {
    console.log('openDebugNode:DebugInputModal',runtimeNodes,runtimeNodeId)
    if (!runtimeNodes || !runtimeEdges) return <></>;

      const runtimeNode =  collect(runtimeNodes).firstWhere('nodeId',runtimeNodeId)
      console.log('openDebugNode:runtimeNode',runtimeNode)
    if (!runtimeNode) return <></>;

    const renderInputs = runtimeNode.inputs;

    return (
        <Drawer 
           isOpen
           placement="right"
           onClose={onClose}
        >
            <DrawerContent>
                <Box flex={'1 0 0'} px={6}>
                  {renderInputs.map((input)=>{
                    if (input.valueType === 'string')
                      return (
                        <>
                          <Textarea bg={'myGray.50'}>

                          </Textarea>
                        </>  
                      )
                     })
                  }
                </Box>
            </DrawerContent>
        </Drawer>
    )
  }, [runtimeNodes]);
  
  return {
    DebugInputModal,
    openDebugNode
  };
};
